package com.apes.scm.masterdata.party.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.plugin.mq.annotation.Consumer;
import com.apes.framework.rop.converter.DateUtils;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.contrast.model.ContrastPartyCode;
import com.apes.scm.masterdata.contrast.repository.ContrastPartyCodeRepository;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.model.SupplierUserLog;
import com.apes.scm.masterdata.party.repository.*;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import lombok.val;
import org.flowable.idm.api.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能：供应商信息
 *
 * @author xul
 * @create 2018-01-23 14:35
 */
@Service("supplierService")
public class SupplierService extends DomainService {
    private static final String ROLE_TYPE = "Supplier";

    @Autowired
    private PartyService partyService;
    @Autowired
    private PartyRoleService partyRoleService;
    @Autowired
    private SupplierRepository supplierRepository;
    @Autowired
    private CorporateSerive corporateSerive;
    @Autowired
    private PartyRoleRepository partyRoleRepository;
    @Autowired
    private SupplierUserLogRepository supplierUserLogRepository;

    @Value("${apes.switched:false}")
    private Boolean switched;

    public Party save(SimpleRequest request) {
        JSONObject json = request.getJO();

        // 名称重复控制
        List<Party> list = SpringManager.getBean(PartyRepository.class).findByRoleIdAnAndName("Supplier", json.getString("name"));
        if (!list.isEmpty()) {
            throw new RuntimeException(json.getString("name") + "名称已存在，编码：" + list.get(0).getPartyRoleByType("Supplier").getId());
        }

        Party party = request.getO(Party.class);
        party.setPartyType("corporate");        // 设置为法人单位
        party.addPartyRole(ROLE_TYPE, party.getSupplierCode());  // 创建角色类型为  Supplier

        // 设置注册省份、注册城市、办公省份、办公城市
        corporateSerive.setCorporateCityAndProvince(party);

        Party result = partyService.saveAndFlush(party, ROLE_TYPE, party.getSupplierCode());
//        result.setSupplierCode(party.getSupplierCode());
        //老系统和新系统供应商相差两位
        result.setOrigin("00" + party.getPartyRoles().stream().filter(partyRole -> partyRole.getRole().getId().equals("Supplier")).findFirst().get().getId());
        result.setSupplierCode(party.getPartyRoles().stream().filter(partyRole -> partyRole.getRole().getId().equals("Supplier")).findFirst().get().getId());

        result = partyService.saveAndFlush(result,ROLE_TYPE,result.getSupplierCode());

        ContrastPartyCodeRepository codeRepository = SpringManager.getBean(ContrastPartyCodeRepository.class);
        ContrastPartyCode contrastPartyCode = new ContrastPartyCode();
        contrastPartyCode.setParty(result);
        contrastPartyCode.setGysid(result.getOrigin());
        codeRepository.saveAndFlush(contrastPartyCode);
        //产生同步至旧系统的body值
        JSONObject body = new JSONObject();
        synSupplier(result,body,request);

        /**
         * 本地调用测试
         * String topic = "event:cm.supplier.synUnifiedExport";
         * EventUtil.sendSynEvent(this, topic, body).stream().findFirst().get();
         */
//        使用MQ发送异步推送旧系统同步创建
//        if(!switched){
            MQUtil.publish("mq.supplier.unified.export","单位客户创建", body);
//        }

        return result;
    }


    // 更新供应商信息
    public Party update(SimpleRequest request) {
        // 获取模型
        Party party = request.getO(Party.class);

        party.setUpdateDate(new Date());

        // 重新更新注册省份、注册城市、办公省份、办公城市（由于目前前端只保存了注册区县，办公区县）
        corporateSerive.setCorporateCityAndProvince(party);

        // 更新相关信息
        Party result = partyService.saveAndFlush(party, ROLE_TYPE, party.getSupplierCode());
        result.setSupplierCode(party.getSupplierCode());

        //产生同步至旧系统的body值
        JSONObject body = new JSONObject();
        synSupplier(result,body,request);

        /**
         * 本地调用测试
         * String topic = "event:cm.supplier.synUnifiedExport";
         * EventUtil.sendSynEvent(this, topic, body).stream().findFirst().get();
         */

        //使用MQ发送异步推送旧系统同步创建
        if(!switched){
            MQUtil.publish("mq.supplier.unified.export","单位客户创建", body);
        }

        return result;
    }

    /**
     * 查询供应商
     */
    public Page<Party> find(SimpleRequest request) {
        String value = request.get("key");
        String partyType = "Supplier";
        Page<Party> partyPage = supplierRepository.find(partyType, "%" + value + "%", PageRequest.of(request.get("page"), request.get("size")));
        partyPage.getContent().stream().forEach(
                (Party party) -> {
                    party.setId(partyService.findOne(party.getId()).getId());
                }
        );
        return partyPage;
    }

    /**
     * 定义供应商查询
     */
    public Page<Party> findAll(SimpleRequest request) {
        Page<Party> partyPage = partyService.findPartyAllByTypeAndRole(request, "corporate", "Supplier");
        return partyPage;
    }

    public String addSupplierRole(SimpleRequest request) {
        return partyRoleService.addPartyTypeAndRoleId(request, "corporate", "Supplier");
    }


    public PartyRole findOne(String id) {
        return partyRoleService.findOne(id, "Supplier");
    }

    /**
     * 根据SUCC查找客户公司信息
     *
     * @param request
     * @return
     */
    public Party findBySUCC(SimpleRequest request) {
        String uscc = request.get("uscc");
        return partyService.findPartyByIdTypeAndIdValueAndRoleId("PIT_USCC", uscc, "Supplier");
    }

    /**
     * 根据Code查找公司信息
     *
     * @param request code 供应商编码
     * @return
     */
    public Party findByCode(SimpleRequest request) {
        return partyService.findPartyByIdTypeAndIdValue("SupplierCode", request.get("code"));
    }

    /**
     * 查询供应商（财务凭证下拉使用）
     *
     * @param request key 条件，公司
     * @return
     */
    public Page<Map<String, String>> findByKeyAndCompany(SimpleRequest request) {
        String value = request.get("key");
        String company = request.get("company");
        return supplierRepository.findByKeyAndCompany(value, PageRequest.of(request.get("page"), request.get("size")));

    }

    /**
     * 根据供应商找对应party
     *
     * @param request
     * @return
     */
    public Party findParyBySupplierId(SimpleRequest request) {
        try {
            JSONObject jo = request.getJO();
            return partyRoleService.findOne(jo.getString("id"), "Supplier").getParty();
        } catch (Exception e) {
            return null;
        }
    }

    public Page findByInternal(SimpleRequest request) {
        Map map = request.getMap();
        Boolean flag = true;

        //判断是否期初入库
         String scene = request.getJO().getJSONObject("group").getJSONArray("filters").getJSONObject(0).getString("value");
        if (scene== null) {
            throw new RuntimeException("未选择凭证类型， 请先选择");
        }
//        if (scene.equals("PO002")) {
//            flag = false;
//        }
        List<Map<String, Object>> condition = new ArrayList<Map<String, Object>>();
        if (map.containsKey("condition")) {
            condition = (List<Map<String, Object>>) map.get("condition");
        }
        if (map.containsKey("key")) {
            Map<String, Object> filter = new HashMap<>();
            String id = (String) map.get("key");
            try {
                Integer.parseInt(id);
                filter.put("field", "id");
            } catch (NumberFormatException e) {
                filter.put("field", "party.name");
            }
            filter.put("operator", "LIKE");
            filter.put("value", id);
            condition.add(filter);
        }
        if ("PO002".equals(scene)) {
            // 默认供应商
            Map defaultSupplier = new HashMap();
            defaultSupplier.put("field", "id");
            defaultSupplier.put("value", "A00000");
            defaultSupplier.put("operator", "EQ");
            condition.add(defaultSupplier);
        }
        // 角色类型
        Map roleParams = new HashMap<>();
        roleParams.put("field", "role.id");
        roleParams.put("operator", "EQ");
        roleParams.put("value", "Supplier");
        condition.add(roleParams);
        // 当事人类型
        Map typeParams = new HashMap<>();
        typeParams.put("field", "party.partyType");
        typeParams.put("operator", "EQ");
        typeParams.put("value", "corporate");
        condition.add(typeParams);
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Page<PartyRole> result = partyRoleRepository.findAll(JpaDsl.toCriteria(condition), PageRequest.of(request.get("page"), request.get("size"), sort));
        Boolean finalFlag = flag;
        List<PartyRole> partyList = result.stream().filter(e -> {
                    if (e.getParty().getPartyRoles().stream().filter(role -> "Company".equals(role.getRole().getId())).count() > 0) {
                        return finalFlag;
                    }
                    return true;
                }
        ).collect(Collectors.toList());
        PageImpl<Map> page = new PageImpl<Map>((List) partyList, result.getPageable(), result.getTotalElements());
        return page;
    }


    /**
     * 查询有效供应商
     * @param request
     */
    public Page<PartyRole> findValidSupplier(SimpleRequest request) {
        JSONArray filters_Array = request.getJO().getJSONObject("group").getJSONArray("filters");
        String id = "";
        String name = "";
        for (int i = 0, iLen = filters_Array.size(); i < iLen; i++) {
            JSONObject filters_Obj = filters_Array.getJSONObject(i);
            id = filters_Obj.getString("value");
            name = filters_Obj.getString("value");
        }
        return partyRoleRepository.findValidSupplier(id, name, PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 查找无内部供应商的供应商
     * @param simpleRequest
     * @return
     */
    public Page<PartyRole> findSupplier(SimpleRequest simpleRequest) {
        JSONObject getJO = simpleRequest.getJO();
        JSONArray filtersArray = getJO.getJSONObject("group").getJSONArray("filters");
        String id = "", noinId = "", scene = "";
        for (int i = 0, iLen = filtersArray.size(); i < iLen; i++) {
            JSONObject filtersObj = filtersArray.getJSONObject(i);
            String field = filtersObj.getString("field");
            String value = filtersObj.getString("value");
            if ("id".equals(field)) {
                id = value;
            } else if ("noinId".equals(field)) {
                noinId = value;
            } else if ("scene".equals(field)) {
                scene = value;
            }
        }
        if ("PO003".equals(scene)) noinId = "1";
        return partyRoleRepository.findSupplier(id, noinId, PageRequest.of(simpleRequest.get("page"), simpleRequest.get("size")));
    }

    // 返厂查询非内部供应商
    public Page<PartyRole> queryNoInnerSupplier(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        Object key = getJO.get("key");
        if (StringUtils.isEmpty(key)) {
            if (getJO.getJSONArray("condition").size() == 0) return partyRoleRepository.purchaseReturnQNoInnerSupplier("004465", PageRequest.of(request.get("page"), request.get("size")));
            key = getJO.getJSONArray("condition").getJSONObject(0).getString("value");
        }
        return partyRoleRepository.purchaseReturnQNoInnerSupplier(key.toString(), "004465", PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 同步老系统供应商 body 数据写入
     * @param party
     * @param body
     * @param request
     */
    public void synSupplier(Party party,JSONObject body,SimpleRequest request){
        JSONObject synSupplier = new JSONObject();

        PartyRole company = request.getCurrentCompany();

        synSupplier.put("GYSID", party.getOrigin());
        synSupplier.put("GYSMC", party.getName());
        synSupplier.put("GYSJC", party.getAbbreviation());

        synSupplier.put("GJID", party.getCorporate().getRegCountry().getId());
        synSupplier.put("SFID", party.getCorporate().getRegProvince().getId().substring(0, party.getCorporate().getRegProvince().getId().length() - 4));
        synSupplier.put("CSID", party.getCorporate().getRegCity().getId().substring(0, party.getCorporate().getRegCity().getId().length() - 2));
        synSupplier.put("QXID", party.getCorporate().getRegCounty().getId());
        synSupplier.put("DZ", party.getCorporate().getRegAddress());

        synSupplier.put("GSID", party.getCorporate().getBelongCompany() == null ? "" : party.getCorporate().getBelongCompany().getId());
        synSupplier.put("KHID", party.getCorporate().getBelongSupplier()== null ? "" : party.getCorporate().getBelongSupplier().getId());
        synSupplier.put("SPGYSBJ", party.getCorporate().isProductProvider() ? 1 : 0);
        synSupplier.put("WLGYSBJ", party.getCorporate().isLogisticsProvider() ? 1 : 0);
        synSupplier.put("FWGYSBJ", party.getCorporate().isServiceProvider() ? 1 : 0);
        synSupplier.put("CCGYSBJ", party.getCorporate().isStorageProvider() ? 1 : 0);
        synSupplier.put("ZFGYSBJ", party.getCorporate().isPayProvider() ? 1 : 0);
        synSupplier.put("YXBJ", party.getCorporate().isValid() ? 1 : 0);
        synSupplier.put("JJGYSBJ", party.getCorporate().isUrgentProvider() ? 1 : 0);
        synSupplier.put("SHGYSBJ", party.getCorporate().isAfterSaleProvider() ? 1 : 0);
        synSupplier.put("NBGYSBJ", party.getCorporate().isInnerProvider() ? 1 : 0);
        synSupplier.put("BXGYSBJ", party.getCorporate().isInsuranceProvider() ? 1 : 0);
        synSupplier.put("CHYXJBJ", party.getCorporate().isShipmentPriority() ? 1 : 0);
        synSupplier.put("TS01", DateUtils.format(party.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
        synSupplier.put("LRR", party.getCreator() != null ? party.getCreator() : request.getSession().getUserName());
        synSupplier.put("LRRQ_SJ", DateUtil.format(party.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));

        //性质编码 不传
//        String description = party.getCorporate().getCompanyNature().getDescription();
//        synSupplier.put("GSXZMC", party.getCorporate().getCompanyNature().getDescription());
//        if (description.equals("有限责任公司")) {
//            synSupplier.put("GSXZID", 1);
//        }
//        if (description.equals("股份有限公司")) {
//            synSupplier.put("GSXZID", 2);
//        }
//        if (description.equals("合伙企业")) {
//            synSupplier.put("GSXZID", 8);
//        }
//        if (description.equals("国有企业")) {
//            synSupplier.put("GSXZID", 4);
//        }
//        if (description.equals("个体户")) {
//            synSupplier.put("GSXZID", 9);
//        }
        if (party.getCorporate().getSupplierLevel()!=null){
            String supplierLevel = party.getCorporate().getSupplierLevel().getDescription();

            if (supplierLevel.equals("A级")) {
                synSupplier.put("DWJB", 0);
            }
            if (supplierLevel.equals("B级")) {
                synSupplier.put("DWJB", 1);
            }
            if (supplierLevel.equals("C级")) {
                synSupplier.put("DWJB", 2);
            }
            if (supplierLevel.equals("D级")) {
                synSupplier.put("DWJB", 3);
            }
            if (supplierLevel.equals("E级")) {
                synSupplier.put("DWJB", 4);
            }
        }

        body.put("Supplier", synSupplier);

        // 生成供应商后要生成 采购组织分配供应商
        JSONObject synCGZZGYS = new JSONObject();
        synCGZZGYS.put("CGZZID", company.getId());
        synCGZZGYS.put("CGZZMC", company.getName());
        synCGZZGYS.put("GYSID", party.getOrigin());
        synCGZZGYS.put("GYSMC", party.getName());
        synCGZZGYS.put("TS01", DateUtils.format(party.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
        synCGZZGYS.put("LRR", party.getCreator() != null ? party.getCreator() : request.getSession().getUserName());
        synCGZZGYS.put("LRRQ_SJ", DateUtil.format(party.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));

        body.put("CGZZGYS", synCGZZGYS);

        // 生成供应商后要生成 供应商注册信息
        JSONObject synGYSZCXX = new JSONObject();
        synGYSZCXX.put("GYSID", party.getOrigin());
        synGYSZCXX.put("GYSMC", party.getName());
        synGYSZCXX.put("GJID", party.getCorporate().getRegCountry().getId());
        synGYSZCXX.put("SFID", party.getCorporate().getRegProvince().getId().substring(0, party.getCorporate().getRegProvince().getId().length() - 4));
        synGYSZCXX.put("CSID", party.getCorporate().getRegCity().getId().substring(0, party.getCorporate().getRegCity().getId().length() - 2));
        synGYSZCXX.put("QXID", party.getCorporate().getRegCounty().getId());
        synGYSZCXX.put("DZ", party.getCorporate().getRegAddress());

        synGYSZCXX.put("KHYH", party.getBank());
        synGYSZCXX.put("ZH", party.getBankAccount());
        synGYSZCXX.put("SH", party.getCorporate().getUscc());
        synGYSZCXX.put("ZZJGDM", party.getCorporate().getUscc());
        synGYSZCXX.put("YZBM",  party.getCorporate().getPostalCode()==null?"无":party.getCorporate().getPostalCode());
        synGYSZCXX.put("ZCHBDW", 0);
        synGYSZCXX.put("FRDB", party.getCorporate().getLegalPerson());
        synGYSZCXX.put("ZCZJ", party.getCorporate().getRegisteredCapital());
        synGYSZCXX.put("ZCZJ_2", party.getCorporate().getRegisteredCapital());

        body.put("GYSZCXX", synGYSZCXX);

        // 生成供应商后要生成 供应商财务信息
        JSONObject synGYSCWXX = new JSONObject();
        synGYSCWXX.put("GYSID", party.getOrigin());
        synGYSCWXX.put("GYSMC", party.getName());
        synGYSCWXX.put("SSLBID", party.getCorporate().getTax().getOrigin());
        synGYSCWXX.put("SSBL", party.getCorporate().getTax().getAmt()/100);
        synGYSCWXX.put("KPBJ", party.getCorporate().isCanInvoice() ? 1 : 0);
        synGYSCWXX.put("FPTT", party.getInvoiceTitle());
        synGYSCWXX.put("FPDZ", party.getInvoiceAddress());
        synGYSCWXX.put("FPDH", party.getInvoicePhone());
        String name = party.getCorporate().getTax().getName();
        if (name.equals("16%增值税")) {
            synGYSCWXX.put("SSLBID", "J9");
        }
        if (name.equals("10%增值税")) {
            synGYSCWXX.put("SSLBID", "J8");
        }
        if (name.equals("13%增值税")) {
            synGYSCWXX.put("SSLBID", "J5");
        }
        if (name.equals("6%增值税")) {
            synGYSCWXX.put("SSLBID", "J4");
        }
        if (name.equals("5%增值税")) {
            synGYSCWXX.put("SSLBID", "J3");
        }
        if (name.equals("3%增值税")) {
            synGYSCWXX.put("SSLBID", "J2");
        }
        if (name.equals("1.5%增值税")) {
            synGYSCWXX.put("SSLBID", "J1");
        }
        if (name.equals("无税")) {
            synGYSCWXX.put("SSLBID", "J0");
        }
        synGYSCWXX.put("ZGKPJE", party.getCorporate().getMaxInvoiceValue());

        body.put("GYSCWXX", synGYSCWXX);
    }

    /**
     * 推送异步消息至老系统
     *
     * @param request
     */
    @Consumer(topic = "mq.supplier.unified.export")
    private void mqUnifiedExport(SimpleRequest request) {
        String topic = "event:cm.supplier.synUnifiedExport";
        EventUtil.sendSynEvent(this, topic, request.getJO()).stream().findFirst().get();
    }

    /**
     * 获取供应商票点
     * @param request
     */
    public Object getSupplierTicketPoint(SimpleRequest request) {
        Map map = request.getMap();
        if (map.containsKey("PRODUCT_ID") && map.get("PRODUCT_ID") != null){
            Product product = SpringManager.getBean(ProductRepository.class).findOne((String) map.get("PRODUCT_ID"));
            map.put("CLASSIFY_ID",product.getClassify().getId());
            map.put("BRAND_ID",product.getBrand().getId());
        }
        map.put("conditionStrategyId", "CG11");
        map.put("SYS_RQ", new Date());
        return this.invoke("condition.execConditionStrategy", map);
    }

    /**
     * 采购价格文件获取售价锁价
     * @param request
     */
    public Object getPriceCGWJ(SimpleRequest request) {
        Map map = request.getMap();
        Product product = SpringManager.getBean(ProductRepository.class).findOne((String) map.get("PRODUCT_ID"));
        Double JG = Double.parseDouble(map.get("JG").toString());
        Double PD = Double.parseDouble(map.get("PD").toString());
        map.put("P001",Arith.round(JG + (JG * (PD /100)),2));
        map.put("CLASSIFY_ID",product.getClassify().getId());
        map.put("BRAND_ID",product.getBrand().getId());
        map.put("conditionStrategyId", "CG03");
        map.put("SYS_RQ", new Date());
        return this.invoke("condition.execConditionStrategy", map);

    }

    /**
     * 获取供应商票点
     * @param companyId
     * @param SupplierId
     * @param productId
     * @return
     */
    public double getSupplierTicketPoint(String companyId, String SupplierId, String productId) {
        JSONObject param = new JSONObject();
        Product product = SpringManager.getBean(ProductRepository.class).findOne(productId);
        param.put("conditionStrategyId", "CG11");
        param.put("SYS_RQ", new Date());
        param.put("SUPPLIER_ID", SupplierId);
        param.put("COMPANY_ID", companyId);
        param.put("BRAND_ID", product.getBrand().getId());
        param.put("CLASSIFY_ID", product.getClassify().getId());
        Object invoke = this.invoke("condition.execConditionStrategy", param);
        JSONObject result = new JSONObject(MapUtil.mapped(invoke));
        return result.getDoubleValue("P101");
    }

    public List getSupplierTicketWarningCount(SimpleRequest request) {
        List<Map> dimensions = new ArrayList();
        dimensions.add(MapUtil.mapper("id", "SUPPLIER_ID", "name", "供应商维度", "formId", "cm.supplier.supplierDimensions"));
        dimensions.add(MapUtil.mapper("id", "SUPPLIER_ID,CLASSIFY_ID", "name", "供应商+品类维度", "formId", "cm.supplierTicket.supplierClassifyDimensions"));
        dimensions.add(MapUtil.mapper("id", "SUPPLIER_ID,CLASSIFY_ID,BRAND_ID", "name", "供应商+品类+品牌维度", "formId", "cm.supplierTicket.supplierClassifyBrandDimensions"));
        String conditionId = "T11";
        List param = new ArrayList();
        for (Map dimension : dimensions) {
            Object invoke = invoke("condition.qryConditionMidTabName", MapUtil.mapper("SYS_DIM_FIELD", dimension.get("id").toString(), "conditionId", conditionId));
            JSONArray array = SpringManager.getBean(AccessProviderDao.class).querySupplierTicketWarningCount(invoke.toString());
            int count = array.getJSONObject(0).getIntValue("COUNT");
            param.add(MapUtil.mapper("LEFTTEXT", dimension.get("name"), "RIGHTTEXT", count,
            "formId", dimension.get("formId").toString()));
        }
        return param;
    }

    public Map getSupplierTicketWarningList(SimpleRequest request) {
        JSONObject jo = request.getJO();
        String conditionId = "T11";
        String queryId = jo.getJSONObject("data").getString("formId");
        Map map = MapUtil.mapper("cm.supplier.supplierDimensions", "SUPPLIER_ID",
                "cm.supplierTicket.supplierClassifyDimensions", "SUPPLIER_ID,CLASSIFY_ID",
                "cm.supplierTicket.supplierClassifyBrandDimensions", "SUPPLIER_ID,CLASSIFY_ID,BRAND_ID");
        String tableName = invoke("condition.qryConditionMidTabName",
                MapUtil.mapper("SYS_DIM_FIELD", map.get(queryId).toString(), "conditionId", conditionId)).toString();
        JSONArray array = new JSONArray();
        if (queryId.equals("cm.supplier.supplierDimensions")) {
            array = SpringManager.getBean(AccessProviderDao.class).supplierDimensions(tableName);
        } else if (queryId.equals("cm.supplierTicket.supplierClassifyDimensions")) {
            array = SpringManager.getBean(AccessProviderDao.class).supplierClassifyDimensions(tableName);
        } else {
            array = SpringManager.getBean(AccessProviderDao.class).supplierClassifyBrandDimensions(tableName);
        }
        Map param = new HashMap();
        param.put("total", array.size());
        param.put("pages", 1);
        param.put("size", array.size());
        param.put("elements", array.size());
        param.put("page", 0);
        param.put("content", array);

        return param;
    }

    public Object findByInternalOrOtherSupplier(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONArray filtersArray = getJO.getJSONObject("group").getJSONArray("filters");
        String value = "";
        for (int i = 0, iLen = filtersArray.size(); i < iLen; i++) {
            JSONObject filtersObj = filtersArray.getJSONObject(i);
            String field = filtersObj.getString("field");
            value = filtersObj.getString("value");
            if ("SUPPLIER".equals(field)) {
                value = value;
            }
        }
        int i = "".equals(value) ? 1 : 0;
        return partyRoleRepository.findByInternalOrOtherSupplier(i,value, PageRequest.of(request.get("page"), request.get("size")));
    }

    public String newSupplierUser(SimpleRequest request){
        JSONObject json = request.getJO();
        String supplierCode = json.getString("supplierCode");
        Integer valid = supplierUserLogRepository.findBySupplierId(supplierCode);
        if (valid != 0) throw new RuntimeException("请勿重复创建供应商平台账号！");


        PartyRole supplier = partyRoleRepository.findOne(supplierCode);
        //记录新增供应商账号创建人
        SupplierUserLog supplierUserLog = new SupplierUserLog();
        supplierUserLog.setCreator(json.getString("user"));
        supplierUserLog.setSupplier(supplier);
        supplierUserLog.setPhone(json.getJSONObject("userinfo").getString("mobileNumber"));
        supplierUserLog.setOrigin(json.getJSONObject("userinfo").getString("origin"));
        supplierUserLogRepository.saveAndFlush(supplierUserLog);


        //收集数据转发供应商平台创建账号
        JSONObject userJSON = request.getJO().getJSONObject("userinfo");
        userJSON.put("person",supplier);
        userJSON.remove("posts");

        //新增供应商账号
        String userName = invoke("sp.user.weirdUser", userJSON);
        if ("调用服务异常。".equals(JSONObject.parseObject(userName).getString("body")))
            throw new RuntimeException(JSONObject.parseObject(userName).getJSONObject("header").getString("message"));
        return JSONObject.parseObject(userName).getString("body");
    }

}
